package com.verisette.ncos.service.card.bizunit;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.corp.agi.common.exception.ProcessException;
import org.corp.agi.service.bean.ProcessContext;
import org.corp.agi.service.bizunit.CommonBusinessUnit;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfWriter;
import com.verisette.ncos.common.ProjectConstant;
import com.verisette.ncos.persistence.domain.MasterBranch;
import com.verisette.ncos.persistence.domain.MasterMember;
import com.verisette.ncos.persistence.domain.MasterTemplate;
import com.verisette.ncos.persistence.domain.MasterUserProfile;
import com.verisette.ncos.web.card.bean.CardCreateBean;

public class CreateCardPreviewByTemplateBU extends CommonBusinessUnit {
	private Logger logger = Logger.getLogger(CreateCardPreviewByTemplateBU.class);
	
	private float width=ProjectConstant.CARD_WIDTH;
	private float height=ProjectConstant.CARD_HEIGHT;
	
	private final String S_WATERMARK_TEXT = "Print@Post";
	
	private final float S_WATERMARK_FONT_SIZE = 24;
	
	private static final Integer[] TEMPLATE_IMG_REQUIRED = {4, 6, 8};
	private static final Integer[] TEMPLATE_DEPT_REQUIRED = {5, 6, 7, 8};
	
	private static final String[] PRINT_TYPE_FLAG = {"th", "en", "th/en"};
	
	@Override
	public void execute(ProcessContext processContext) throws ProcessException {
		if(logger.isInfoEnabled()) logger.info( this.getClass().getSimpleName() + ": execute" );
		
		MasterUserProfile userBean = (MasterUserProfile)processContext.getUserBean();
		CardCreateBean cardCreateBean = (CardCreateBean)processContext.getOriginalRequest().getValueObject();
		String userPDFPathDir = ProjectConstant.APP_TEMP_PDF_PREVIEW_FOLDER;
		String fullPDFPathFile = userPDFPathDir + "\\" + cardCreateBean.getOrder().getPdfPath();
		
		Rectangle pagesize = new Rectangle(width, height);
		Document document = new Document(pagesize, 0f, 0f, 0f, 0f);
		PdfWriter writer = null;
		
		File output=null;
		try{
			File dir = new File(userPDFPathDir);
			if(!dir.exists()) dir.mkdirs();
			
			output = new File(fullPDFPathFile);
			writer = PdfWriter.getInstance(document, new FileOutputStream(output));
			FontFactory.register(ProjectConstant.FONT_PSLPRO_NORMAL, ProjectConstant.FONT_NAME_PSLPRO_NORMAL);
			FontFactory.register(ProjectConstant.FONT_PSLPRO_BOLD, ProjectConstant.FONT_NAME_PSLPRO_BOLD);
			FontFactory.register(ProjectConstant.FONT_PSLPRO_ITALIC, ProjectConstant.FONT_NAME_PSLPRO_ITALIC);
			
	        document.open();
	        
	        Image personalPic;
	        Image backgroundPic;
	        float factor=0f;

    		String currentPageLanguage = "th";
    		
	        String name = "";
	        String position = "";
	        String dept = "";

    		String branchName = "";
    		String branchAddr = "";
    		String branchTel = "";
    		//String branchEmail = "e-mail : somchai.th@thailandpost.co.th";
//    		String branchEmail = "";
//			if(StringUtils.isNotBlank(userBean.getUspEmail())){
//    			branchEmail = "e-mail : " + userBean.getUspEmail();
//    		}
    		
    		MasterBranch branch = userBean.getMasterBranch();
    		boolean isDone = false;
    		String printTypeName = PRINT_TYPE_FLAG[Integer.valueOf(cardCreateBean.getPrintType())];
        	if(printTypeName.indexOf(currentPageLanguage)>-1){
        		if("th".equals(printTypeName)) isDone=true;
		        if(cardCreateBean!=null && cardCreateBean.getOrder().getMasterMember()!=null){
		        	name = String.format("%s %s", cardCreateBean.getOrder().getMasterMember().getMmbFnameTh(), cardCreateBean.getOrder().getMasterMember().getMmbLnameTh());
		        	position = cardCreateBean.getOrder().getMasterMember().getMmbPositionTh();
		        	dept = cardCreateBean.getOrder().getMasterMember().getMmbDeptTh();
		        }
	    		
	    		if(branch!=null){
	    			if(StringUtils.isNotBlank(branch.getBranchNameTh())){
	    				branchName = branch.getBranchNameTh();
	    			}
	    			if(StringUtils.isNotBlank(branch.getBranchAddrTh()) && StringUtils.isNotBlank(branch.getBranchZipCode())){
	    				branchAddr = branch.getBranchAddrTh() + " " + branch.getBranchZipCode();
	    			}
	    			if(StringUtils.isNotBlank(branch.getBranchTel1Th())){
	    				branchTel = "โทรศัพท์ : " + branch.getBranchTel1Th();
	    			}
	    		}
        	}
    		
    		MasterTemplate template = cardCreateBean.getOrder().getMasterTemplate();
    		MasterMember member = cardCreateBean.getOrder().getMasterMember();
    		boolean isMmbPictureRequired = (cardCreateBean.getOrder().getMasterTemplate()!=null && "Y".equals(cardCreateBean.getOrder().getMasterTemplate().getMtpImgRequired()));
    		
    		boolean imgRequired =ArrayUtils.contains(TEMPLATE_IMG_REQUIRED, template.getMtpId()); 
    		float noImgRequiredSub = 0f;
    		if(!imgRequired){
    			noImgRequiredSub = 15f;
    		}
	        do{
	        	if(!"".equals(name)){
		        	backgroundPic = Image.getInstance(String.format(ProjectConstant.APP_IMAGES_FOLDER + "\\BG\\BG_Final_printpost.tif"));
	        		if (backgroundPic.getScaledWidth() > width || backgroundPic.getScaledHeight() > height) {
	        			backgroundPic.scaleToFit(width, height);
	        		}
	        		document.add(backgroundPic);
	        		PdfContentByte over = writer.getDirectContent();
	        		if(imgRequired){
			        	if(isMmbPictureRequired && member!=null && member.getMmbPicturePath()!=null && !"".equals(member.getMmbPicturePath())){
			        		personalPic = Image.getInstance(ProjectConstant.APP_TEMP_IMG_FOLDER + "\\" + member.getMmbPicturePath());
			        		float w=80.65f, h=46.62f;
//			        		float w=60f, h=46.62f;
			        		float left=198.44f, buttom=99f;
			        		personalPic.scaleToFit(w, h);
			        		personalPic.setAbsolutePosition(left, buttom);
			        		personalPic.setBorder(Image.BOX);
			        		personalPic.setBorderWidth(0.5f);
			        		over.saveState();
			        		over.addImage(personalPic);
			        		over.restoreState();
			        	}
	        		}
	        		
	        		over.beginText();
	        		BaseFont font = BaseFont.createFont(ProjectConstant.FONT_PSLPRO_NORMAL, ProjectConstant.EXPORT_ENCODE_TIS620, BaseFont.EMBEDDED);
	        		BaseFont fontItalic = BaseFont.createFont(ProjectConstant.FONT_PSLPRO_ITALIC, ProjectConstant.EXPORT_ENCODE_TIS620, BaseFont.EMBEDDED);
	        		over.setFontAndSize(font,14);
	        		over.showTextAligned(Element.ALIGN_RIGHT, name, 235, 89+noImgRequiredSub, 0);
	        		over.setFontAndSize(fontItalic, 11);
	        		over.showTextAligned(Element.ALIGN_RIGHT, position, 235, 78+noImgRequiredSub, 0);
	        		if(ArrayUtils.contains(TEMPLATE_DEPT_REQUIRED, template.getMtpId())){
	            		over.setFontAndSize(fontItalic, 11);
	            		over.showTextAligned(Element.ALIGN_RIGHT, dept, 235, 67+noImgRequiredSub, 0);
	        		}
	        		
	        		float part2start = 60;
	        		over.setFontAndSize(font, 11);
	        		over.showTextAligned(Element.ALIGN_RIGHT, branchName, 236, part2start-13-factor, 0);
	        		over.showTextAligned(Element.ALIGN_RIGHT, branchAddr, 236, part2start-23-factor, 0);
	        		over.showTextAligned(Element.ALIGN_RIGHT, branchTel, 236, part2start-33-factor, 0);
//	        		over.showTextAligned(Element.ALIGN_RIGHT, branchEmail, 236, part2start-43-factor, 0);
	        		over.showTextAligned(Element.ALIGN_RIGHT, "e-mail : "+member.getMmbEmail(), 236, part2start-43-factor, 0);
	        		
		        	//Watermark
	        		over.saveState();
	                PdfGState gs1 = new PdfGState();
	                gs1.setFillOpacity(0.3f);
	                over.setGState(gs1);
	        		Font FONT = new Font(FontFamily.HELVETICA, S_WATERMARK_FONT_SIZE, Font.BOLD, new GrayColor(0.75f));
		        	ColumnText.showTextAligned(over,
			        		Element.ALIGN_CENTER, new Phrase(S_WATERMARK_TEXT, FONT),
			              110.5f, part2start+20-factor, 30);
		        	over.restoreState();
	        		
	        		over.endText();
	        	}
	        	
        		if(isDone) break;
        		if("".equals(member.getMmbFnameEn())) break;
        		//English
        		if(member!=null){
	            	name = String.format("%s %s",member.getMmbFnameEn(), member.getMmbLnameEn());
	            	position = member.getMmbPositionEn();
	            	dept = member.getMmbDeptEn();
        		}

        		branchName = "";
        		branchAddr = "";
        		branchTel = "";
        		
        		if(branch!=null){
        			if(StringUtils.isNotBlank(branch.getBranchNameEn())){
        				branchName = branch.getBranchNameEn();
        			}
        			if(StringUtils.isNotBlank(branch.getBranchAddrEn()) && StringUtils.isNotBlank(branch.getBranchZipCode())){
        				branchAddr = branch.getBranchAddrEn() + " " + branch.getBranchZipCode() + " Thailand";
        			}
        			if(StringUtils.isNotBlank(branch.getBranchTel1En())){
        				branchTel = "Tel : " + branch.getBranchTel1En();
        			}
        		}
        		currentPageLanguage="en";
        		isDone = true;
        		document.newPage();
	        }while(true);
	        document.close();
		}catch(Exception ex){
			logger.error(ex.getStackTrace());
			ex.printStackTrace();
		}finally{
			if(writer!=null) try{ writer.close(); }catch(Exception ex){ logger.error("writer.close() fail."); }
		}
		
		if(logger.isDebugEnabled()){
			logger.debug("fullPDFPathFile::" + fullPDFPathFile);
			logger.debug("PDF (java.io.File)output::" + output);
		}
		
//		processContext.setValueObject(output);
	}
}